/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.wyh.intelcheckbash.bluetoothchat;

import android.app.ActionBar;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.HttpUtil;
import com.example.wyh.intelcheckbash.LocalStorage;
import com.example.wyh.intelcheckbash.MainActivity;
import com.example.wyh.intelcheckbash.R;
import com.example.wyh.intelcheckbash.SeismicActivity;
import com.example.wyh.intelcheckbash.common.CommonUtil;
import com.example.wyh.intelcheckbash.common.logger.Log;
import com.example.wyh.intelcheckbash.task.CheckDefectActivity;
import com.example.wyh.intelcheckbash.task.TaskCheckActivity;
import com.example.wyh.intelcheckbash.temptemperature.ThermometricActivity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Set;

/**
 * This fragment controls Bluetooth to communicate with other devices.
 */
public class BluetoothChatFragment extends Fragment {

    private static final String TAG = "BluetoothChatFragment";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
    private static final int REQUEST_ENABLE_BT = 3;

    // Layout Views
    private ListView mConversationView;
//    private EditText mOutEditText;
    public byte[] mTempTestSeismicDataByte = new byte[0];
    public byte[] mTempTestOneData = new byte[0];

    public byte[] mTempThermoByte = new byte[0];
    public byte[] mTestBatteryLevel = new byte[0];

    /**
     * Name of the connected device
     */
    private String mConnectedDeviceName = null;

    /**
     * Array adapter for the conversation thread
     */
    private ArrayAdapter<String> mConversationArrayAdapter;

    /**
     * String buffer for outgoing messages
     */
    private StringBuffer mOutStringBuffer;

    /**
     * Local Bluetooth adapter
     */
    private BluetoothAdapter mBluetoothAdapter = null;

    /**
     * Member object for the chat services
     */
    public BluetoothChatService mChatService = null;

    public int mReciveCount = 0;

    public Boolean mIsConnectedBlueTooth = false;
    public int position;

    private Context mContext;
    public void setContext(Context context)
    {
        mContext = context;
    }


    private String mTestType = null;//"tempTestSeismic"或者"tempTestThermo"
    public void  setTestType(String type)
    {
        mTestType = type;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            FragmentActivity activity = getActivity();
            Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            activity.finish();
        }


//        new AsyncTask<Void, Void, Void>() {
//
//            @Override
//            protected Void doInBackground(Void... params) {
//                try {
//                    Thread.sleep(2000);
//                } catch (InterruptedException ex) {
//                }
//                return null;
//            }
//
//            @Override
//            protected void onPostExecute(Void result){
//                if(isAdded()){
//                    getResources().getString(R.string.app_name);
//                }
//            }
//
//        }.execute();
    }


    @Override
    public void onStart() {
        super.onStart();
        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult

        if(mBluetoothAdapter==null) // Checking Bluetooth Device install or not
        {
            Toast.makeText(getContext(),"Bluetooth is not available",Toast.LENGTH_SHORT).show();
        }

        else{

            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
                android.util.Log.e("onStart REQUEST_ENABLE_BT","REQUEST_ENABLE_BT  success");
                // Otherwise, setup the chat session
            } else if (mChatService == null) {
                setupChat();
                android.util.Log.e("onStart setupChat","setupChat");
            }

        }
//        BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();
//        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
//        android.util.Log.e("===============pairedDevices",pairedDevices.toString());
//        for (BluetoothDevice device : pairedDevices) {
//            connectDevice(device.getAddress(), true);
//        }
    }

   /* @Override
    public void onStart() {
        super.onStart();
        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the chat session
        } else if (mChatService == null) {
            setupChat();
        }
    }*/

    @Override
    public void onDestroy() {
        mIsConnectedBlueTooth = false;
        if (mChatService != null) {
            mChatService.stop();
        }
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
                // Start the Bluetooth chat services
                mChatService.start();
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_bluetooth_chat, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mConversationView = (ListView) view.findViewById(R.id.in);
//        mOutEditText = (EditText) view.findViewById(R.id.edit_text_out);
    }

    /**
     * Set up the UI and background operations for chat.
     */
    private void setupChat() {
        Log.d(TAG, "setupChat()");

        // Initialize the array adapter for the conversation thread
        mConversationArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.message);

        mConversationView.setAdapter(mConversationArrayAdapter);

        // Initialize the compose field with a listener for the return key
//        mOutEditText.setOnEditorActionListener(mWriteListener);

        // Initialize the send button with a listener that for click events

        // Initialize the BluetoothChatService to perform bluetooth connections
        mChatService = new BluetoothChatService(getActivity(), mHandler);

        // Initialize the buffer for outgoing messages
        mOutStringBuffer = new StringBuffer("");
    }

    /**
     * Makes this device discoverable.
     */

    private void ensureDiscoverable() {
        if (mBluetoothAdapter.getScanMode() !=
                BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    /**
     * Sends a message.
     *
     *
     */
    public void sendMessage(byte[] byteMsg) {
//        android.util.Log.e("mm","happy==========");
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            HttpUtil.showToast(getActivity(), "你没有连接蓝牙设备", 500);
//            Toast.makeText(getActivity(), "You are not connected to a device", Toast.LENGTH_SHORT).show();
            return;
        }
        mChatService.write(byteMsg);
    }

    /**
     * The action listener for the EditText widget, to listen for the return key
     */
//    private TextView.OnEditorActionListener mWriteListener
//            = new TextView.OnEditorActionListener() {
//        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
//            // If the action is a key-up event on the return key, send the message
//            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
//                String message = view.getText().toString();
//                sendMessage(message);
//            }
//            return true;
//        }
//    };

    /**
     * Updates the status on the action bar.
     *
     * @param resId a string resource ID
     */
    private void setStatus(int resId) {
        FragmentActivity activity = getActivity();
        if (null == activity) {
            return;
        }
        final ActionBar actionBar = activity.getActionBar();
        if (null == actionBar) {
            return;
        }
        actionBar.setSubtitle(resId);
    }

    /**
     * Updates the status on the action bar.
     *
     * @param subTitle status
     */
    private void setStatus(CharSequence subTitle) {
        FragmentActivity activity = getActivity();
        if (null == activity) {
            return;
        }
        final ActionBar actionBar = activity.getActionBar();
        if (null == actionBar) {
            return;
        }
        actionBar.setSubtitle(subTitle);
    }


    public static byte[] byteMerger(byte[] byte_1, byte[] byte_2){
//        byte_1 = new byte[] {68, 65, 84, 65, 32, 15, -58, 14};
//        byte_2 = new byte[] {68, 65, 84, 65, 35, 15, -67, 14, 113, 13, 96};

        byte[] byte_3 = new byte[byte_1.length+byte_2.length - 4 - 1];
        System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
        System.arraycopy(byte_2, 4, byte_3, byte_1.length, byte_2.length - 4 - 1);
//        System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length - 4);
        return byte_3;
    }



    /**
     * The Handler that gets information back from the BluetoothChatService
     */
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            FragmentActivity activity = getActivity();

            switch (msg.what) {
                case Constants.MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BluetoothChatService.STATE_CONNECTED:
                            try {
                                setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
                                mConversationArrayAdapter.clear();
                            }catch (Exception e)
                            {
                                android.util.Log.e("------------",e.toString());
                            }

                            break;
                        case BluetoothChatService.STATE_CONNECTING:
                            setStatus(R.string.title_connecting);
                            break;
                        case BluetoothChatService.STATE_LISTEN:
                        case BluetoothChatService.STATE_NONE:
                            setStatus(R.string.title_not_connected);
                            break;
                    }
                    break;
                case Constants.MESSAGE_WRITE:
                    byte[] writeBuf = (byte[]) msg.obj;
                    // construct a string from the buffer
                    String writeMessage = new String(writeBuf);
//                    android.util.Log.e("===================adfasdfsdf","====="+writeMessage);
//                    mTempTestSeismicDataByte = new byte[0];
//                    mConversationArrayAdapter.add("Me:  " + writeMessage);
                    break;
                case Constants.MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;
                    mTempTestOneData = new byte[0];
//                    android.util.Log.e("接受数据====灵敏度：",Arrays.toString(readBuf));
//                    android.util.Log.e("接受数据====",Arrays.toString(CommonUtil.bytesToHexStrings(readBuf)));
                    // construct a string from the valid bytes in the buffer
                    if (readBuf[0] == 66 && readBuf[1] == 70 && readBuf[2] == 111 && readBuf[3] == 107 && mTestType.equals("tempTestSeismic") )
                    {
                        SeismicActivity seismicActivity = (SeismicActivity)mContext;
                        seismicActivity.reviceAVDData();
                    }
                    if (readBuf[0] == 68 && readBuf[1] == 65 && readBuf[2] == 84 && readBuf[3] == 65 && mTestType.equals("tempTestSeismic") )
                    {
                        mReciveCount ++;
                        mTempTestSeismicDataByte = byteMerger(mTempTestSeismicDataByte,readBuf);
                        mTempTestOneData = byteMerger(mTempTestOneData,readBuf);

                        SeismicActivity seismicActivity = (SeismicActivity)mContext;
                        seismicActivity.reviceAVDData();
                    }
                    //读取温度数据
                    if (readBuf[0] == 84 && readBuf[1] == 80 && readBuf[2] == 77 && readBuf[3] == 73 && readBuf[4] == 2 && mTestType.equals("tempTestThermo"))
                    {
                        mTempThermoByte = new byte[] {readBuf[5],readBuf[6]};
//                        android.util.Log.e("mTempThermoByte",Arrays.toString(CommonUtil.bytesToHexStrings(mTempThermoByte)));
                        ThermometricActivity thermometricActivity = (ThermometricActivity)mContext;
                        thermometricActivity.dealThermData(mTempThermoByte);
                    }
                    if (readBuf[0] == 66 && readBuf[1]==76 && mTestType.equals("testBatteryLevel"))
                    {
                        mTestBatteryLevel = new byte[]{readBuf[2],readBuf[3]};
                        try {
                            MainActivity mainActivity = (MainActivity)activity;
                            mainActivity.showBatteryLevel(mTestBatteryLevel);
                        }catch (Exception e)
                        {
                            android.util.Log.e("mainActivity"+"cannot be cast to",e.getMessage());
                        }

                    }
                    if (readBuf[0] == 83 && readBuf[1]==69 & readBuf[2] == 78 && readBuf[3] == 82)
                    {
                        SeismicActivity seismicActivity = (SeismicActivity) mContext;
                        byte[] reviceSern = new byte[]{readBuf[4],readBuf[5],readBuf[6],readBuf[7],readBuf[8],readBuf[9],readBuf[10]};
                        seismicActivity.showSERN(reviceSern);
                    }

                    break;
                case Constants.MESSAGE_DEVICE_NAME:
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
                    if (null != activity) {
                        HttpUtil.showToast(getActivity(), "成功连接到设备 "
                                + mConnectedDeviceName, 500);
//                        Toast.makeText(activity, "成功连接到设备 "
//                                + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                        mIsConnectedBlueTooth = true;
                        try {
                            MainActivity mainActivity = (MainActivity)activity;
                            mainActivity.updatebatteryLevel();
                        }catch (Exception e)
                        {
                            android.util.Log.e("MainActivity Exception",e.getMessage());
                        }
                        //// TODO: 17/12/26 巡检任务中测量尝试连接
                        try {
                            if (mTestType.equals("TaskCheckActivityTestThermom"))
                            {
                                try {
                                    TaskCheckActivity taskCheckActivity = (TaskCheckActivity)mContext;
                                    taskCheckActivity.bluetoothConnectSuccessJumpToTestThermom(position);
                                }catch (Exception e)
                                {

                                }
                            }

                            else if (mTestType.equals("TaskCheckActivityTestSeismic"))
                            {
                                try {
                                    TaskCheckActivity taskCheckActivity = (TaskCheckActivity)mContext;
                                    taskCheckActivity.bluetoothConnectSuccessJumpToTestSeismic(position);
                                }catch (Exception e)
                                {

                                }
                            }
                        }catch (Exception e)
                        {
                            android.util.Log.e("TaskCheckActivityTest",e.getMessage());
                        }
                        //// TODO: 17/12/26 异常点中测量尝试连接
                        try {
                            if (mTestType.equals("CheckDefectActivityTestThermom"))
                            {
                                try {
                                    CheckDefectActivity taskCheckActivity = (CheckDefectActivity)mContext;
                                    taskCheckActivity.bluetoothConnectSuccessJumpToTestThermom(position);
                                }catch (Exception e)
                                {

                                }
                            }

                            else if (mTestType.equals("CheckDefectActivityTestSeismic"))
                            {
                                try {
                                    CheckDefectActivity taskCheckActivity = (CheckDefectActivity)mContext;
                                    taskCheckActivity.bluetoothConnectSuccessJumpToTestSeismic(position);
                                }catch (Exception e)
                                {

                                }
                            }
                        }catch (Exception e)
                        {
                            android.util.Log.e("CheckDefectActivityTest",e.getMessage());
                        }
                    }
                    break;
                case Constants.MESSAGE_TOAST:
                    if (null != activity) {
                        try {
                            MainActivity mainActivity = (MainActivity)activity;
                            mainActivity.updateBatteryStatus();
                        }catch (Exception e)
                        {

                        }
                        mTestType = null;
                        mIsConnectedBlueTooth = false;
                        if (msg.getData().getString(Constants.TOAST).equals("未能成功连接蓝牙传感器"))
                        {
                            MainActivity mainActivity = (MainActivity)activity;
                            mainActivity.initBlueFragment();
                        }
                        HttpUtil.showToast(getActivity(), msg.getData().getString(Constants.TOAST), 500);
                    }
                    break;
            }
        }
    };

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        android.util.Log.e("onActivityResult resultCode","requestCode"+  requestCode);
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE_SECURE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    String address = data.getExtras()
                            .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    connectDevice(address, true);
                    LocalStorage.saveString(getActivity(),"blueToothAddress",address);
                }
                break;
            case REQUEST_CONNECT_DEVICE_INSECURE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    String address = data.getExtras()
                            .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    connectDevice(address, false);
                }
                break;
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    // Bluetooth is now enabled, so set up a chat session
                    setupChat();
                } else {
                    // User did not enable Bluetooth or an error occurred
                    Log.d(TAG, "BT not enabled");
                    Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
                            Toast.LENGTH_SHORT).show();
                    getActivity().finish();
                }
        }
    }

    /**
     * Establish connection with other divice
     *
//     * @param data   An {@link Intent} with {@link DeviceListActivity#EXTRA_DEVICE_ADDRESS} extra.
     * @param secure Socket Security type - Secure (true) , Insecure (false)
     */
    private void connectDevice(String address, boolean secure) {
        // Get the device MAC address

        // Get the BluetoothDevice object
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        // Attempt to connect to the device
        mChatService.connect(device, secure);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.bluetooth_chat, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return false;
    }

    public void selectPairedBlueTooth()
    {
        Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
        startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
    }
    public void connectDeviceWithAddress(String address)
    {
        connectDevice(address,true);
    }

}
